import 'package:flutter/material.dart';
import 'package:myapp/generated/app_strings.dart';
import 'package:myapp/src/route/ai/chat/ai_model_service.dart';
import 'package:myapp/src/route/ai/chat/ai_personality.dart';
import 'package:myapp/src/route/ai/chat/chat_message.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'dart:io';

class AIChatPage extends StatefulWidget {
  const AIChatPage({Key? key}) : super(key: key);

  @override
  _AIChatPageState createState() => _AIChatPageState();
}

class _AIChatPageState extends State<AIChatPage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final FocusNode _focusNode = FocusNode();
  final List<ChatMessage> _messages = [];
  bool _isTyping = false;
  bool _isInputFocused = false;
  AIPersonality _currentPersonality = AIPersonality.defaultPersonality;
  final ImagePicker _imagePicker = ImagePicker();
  final Map<String, VideoPlayerController> _videoControllers = {};

  // 配色方案
  static const Color _primaryGradientStart = Color(0xFF667eea);
  static const Color _primaryGradientEnd = Color(0xFF764ba2);
  static const Color _userMessageGradientStart = Color(0xFF667eea);
  static const Color _userMessageGradientEnd = Color(0xFF764ba2);
  static const Color _aiMessageBg = Color(0xFFF5F7FA);
  static const Color _backgroundGradientStart = Color(0xFFF8F9FA);
  static const Color _backgroundGradientEnd = Color(0xFFE9ECEF);

  @override
  void initState() {
    super.initState();
    _loadChatHistory();
    _initializeAIModel();
    _focusNode.addListener(() {
      setState(() {
        _isInputFocused = _focusNode.hasFocus;
      });
    });
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _focusNode.dispose();
    for (var controller in _videoControllers.values) {
      controller.dispose();
    }
    _videoControllers.clear();
    AIModelService.dispose();
    super.dispose();
  }

  Future<void> _initializeAIModel() async {
    try {
      await AIModelService.initialize();
    } catch (e) {
      print('Error initializing AI model: $e');
    }
  }

  Future<void> _loadChatHistory() async {
    // 实现历史记录加载逻辑
  }

  void _scrollToBottom({VoidCallback? onComplete}) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        ).then((_) {
          onComplete?.call();
        });
      } else {
        onComplete?.call();
      }
    });
  }

  Future<void> _handleSubmitted(String text) async {
    if (text.trim().isEmpty) return;

    setState(() {
      _messages.add(ChatMessage.text(
        content: text,
        isUser: true,
      ));
    });

    _messageController.clear();
    
    _scrollToBottom(onComplete: () {
      _focusNode.requestFocus();
    });

    setState(() {
      _isTyping = true;
    });

    try {
      final response = await AIModelService.generateTextResponse(
        text,
        _currentPersonality.traits,
      );
      
      setState(() {
        _messages.add(ChatMessage.text(
          content: response,
          isUser: false,
        ));
        _isTyping = false;
      });
      
      _scrollToBottom(onComplete: () {
        _focusNode.requestFocus();
      });
    } catch (e) {
      setState(() {
        String errorMessage = '抱歉，AI服务暂时不可用。';
        if (e.toString().contains('API Key') || e.toString().contains('配置')) {
          errorMessage = '请先配置AI API Key。\n\n'
              '推荐使用智谱AI（免费额度充足，国内可访问）：\n'
              '1. 访问 https://open.bigmodel.cn/\n'
              '2. 注册/登录账号\n'
              '3. 创建API Key\n'
              '4. 在 ai_model_service.dart 中设置 _zhipuApiKey\n\n'
              '其他选项：通义千问、文心一言等';
        } else if (e.toString().contains('timeout') || e.toString().contains('超时')) {
          errorMessage = '请求超时，请检查网络连接后重试。';
        } else {
          errorMessage = '错误: ${e.toString()}';
        }
        _messages.add(ChatMessage.text(
          content: errorMessage,
          isUser: false,
        ));
        _isTyping = false;
      });
      print('AI聊天错误: $e');
      
      _scrollToBottom(onComplete: () {
        _focusNode.requestFocus();
      });
    }
  }

  Future<void> _handleImagePick() async {
    try {
      final XFile? image = await _imagePicker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        setState(() {
          _messages.add(ChatMessage.image(
            content: '发送了一张图片',
            isUser: true,
            imagePath: image.path,
          ));
        });

        final aiImage = await AIModelService.generateImage('生成一张相关的图片');
        if (aiImage.isNotEmpty) {
          setState(() {
            _messages.add(ChatMessage.image(
              content: '这是AI生成的图片',
              isUser: false,
              imagePath: 'path_to_saved_image',
            ));
          });
        }
      }
    } catch (e) {
      print('Error picking image: $e');
    }
  }

  Future<void> _handleVideoPick() async {
    try {
      final XFile? video = await _imagePicker.pickVideo(source: ImageSource.gallery);
      if (video != null) {
        setState(() {
          _messages.add(ChatMessage.video(
            content: '发送了一个视频',
            isUser: true,
            videoPath: video.path,
          ));
        });

        setState(() {
          _messages.add(ChatMessage.text(
            content: '视频已收到。目前AI视频生成功能暂未实现。',
            isUser: false,
          ));
        });
      }
    } catch (e) {
      print('Error picking video: $e');
    }
  }

  void _openPersonalitySettings() {
    // 创建控制器，绑定当前人格的值
    final nameController = TextEditingController(text: _currentPersonality.name);
    final descriptionController = TextEditingController(text: _currentPersonality.description);
    
    // 创建滑块值变量
    double friendliness = _currentPersonality.traits['友好度'] ?? 0.8;
    double professionalism = _currentPersonality.traits['专业度'] ?? 0.7;
    double humor = _currentPersonality.traits['幽默感'] ?? 0.5;

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          title: Row(
            children: [
              Icon(Icons.person, color: _primaryGradientStart),
              const SizedBox(width: 8),
              const Text('AI人格设定', style: TextStyle(fontWeight: FontWeight.bold)),
            ],
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                TextField(
                  controller: nameController,
                  decoration: InputDecoration(
                    labelText: '名称',
                    prefixIcon: const Icon(Icons.label),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    filled: true,
                    fillColor: Colors.grey.shade50,
                  ),
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: descriptionController,
                  decoration: InputDecoration(
                    labelText: '描述',
                    prefixIcon: const Icon(Icons.description),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    filled: true,
                    fillColor: Colors.grey.shade50,
                  ),
                  maxLines: 2,
                ),
                const SizedBox(height: 24),
                const Divider(),
                const SizedBox(height: 16),
                const Text(
                  '人格特征',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 16),
                _buildTraitSlider(
                  label: '友好度',
                  value: friendliness,
                  icon: Icons.favorite,
                  color: Colors.red,
                  onChanged: (value) {
                    setDialogState(() {
                      friendliness = value;
                    });
                  },
                ),
                const SizedBox(height: 16),
                _buildTraitSlider(
                  label: '专业度',
                  value: professionalism,
                  icon: Icons.school,
                  color: Colors.blue,
                  onChanged: (value) {
                    setDialogState(() {
                      professionalism = value;
                    });
                  },
                ),
                const SizedBox(height: 16),
                _buildTraitSlider(
                  label: '幽默感',
                  value: humor,
                  icon: Icons.sentiment_very_satisfied,
                  color: Colors.orange,
                  onChanged: (value) {
                    setDialogState(() {
                      humor = value;
                    });
                  },
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                nameController.dispose();
                descriptionController.dispose();
                Navigator.pop(context);
              },
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                // 保存人格设定
                setState(() {
                  _currentPersonality = AIPersonality.createCustom(
                    name: nameController.text.isEmpty 
                        ? '默认AI助手' 
                        : nameController.text,
                    description: descriptionController.text.isEmpty
                        ? '一个友好、专业的AI助手'
                        : descriptionController.text,
                    traits: {
                      '友好度': friendliness,
                      '专业度': professionalism,
                      '幽默感': humor,
                    },
                    conversationStyle: _currentPersonality.conversationStyle,
                  );
                });
                nameController.dispose();
                descriptionController.dispose();
                Navigator.pop(context);
                
                // 显示保存成功提示
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: const Row(
                      children: [
                        Icon(Icons.check_circle, color: Colors.white),
                        SizedBox(width: 8),
                        Text('人格设定已保存'),
                      ],
                    ),
                    backgroundColor: Colors.green,
                    behavior: SnackBarBehavior.floating,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                );
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryGradientStart,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              ),
              child: const Text('保存', style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTraitSlider({
    required String label,
    required double value,
    required IconData icon,
    required Color color,
    required ValueChanged<double> onChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(icon, color: color, size: 20),
            const SizedBox(width: 8),
            Text(
              label,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            ),
            const Spacer(),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                '${(value * 100).toInt()}%',
                style: TextStyle(
                  color: color,
                  fontWeight: FontWeight.bold,
                  fontSize: 12,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            activeTrackColor: color,
            inactiveTrackColor: color.withOpacity(0.3),
            thumbColor: color,
            overlayColor: color.withOpacity(0.2),
            trackHeight: 4,
            thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 10),
          ),
          child: Slider(
            value: value,
            min: 0.0,
            max: 1.0,
            divisions: 100,
            label: '${(value * 100).toInt()}%',
            onChanged: onChanged,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [_backgroundGradientStart, _backgroundGradientEnd],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildModernAppBar(),
              Expanded(
                child: Container(
                  decoration: const BoxDecoration(
                    color: Colors.transparent,
                  ),
                  child: ListView.builder(
                    controller: _scrollController,
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    itemCount: _messages.length + (_isTyping ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index == _messages.length) {
                        return _buildTypingIndicator();
                      }
                      return _buildMessage(_messages[index]);
                    },
                  ),
                ),
              ),
              _buildInputArea(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildModernAppBar() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [_primaryGradientStart, _primaryGradientEnd],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        boxShadow: [
          BoxShadow(
            color: _primaryGradientStart.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Icon(Icons.smart_toy, color: Colors.white, size: 24),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _currentPersonality.name,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 0.5,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Row(
                    children: [
                      if (_currentPersonality.description.isNotEmpty) ...[
                        Expanded(
                          child: Text(
                            _currentPersonality.description,
                            style: TextStyle(
                              color: Colors.white.withOpacity(0.8),
                              fontSize: 11,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 8),
                      ],
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          _isTyping ? '正在输入...' : '在线',
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.9),
                            fontSize: 11,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            _buildIconButton(
              icon: Icons.person_outline,
              onPressed: _openPersonalitySettings,
              tooltip: '人格设定',
            ),
            const SizedBox(width: 8),
            _buildIconButton(
              icon: Icons.delete_outline,
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                    title: const Text('清除对话', style: TextStyle(fontWeight: FontWeight.bold)),
                    content: const Text('确定要清除所有对话记录吗？'),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: const Text('取消'),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          setState(() {
                            _messages.clear();
                            AIModelService.clearHistory();
                          });
                          Navigator.pop(context);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                        ),
                        child: const Text('确定', style: TextStyle(color: Colors.white)),
                      ),
                    ],
                  ),
                );
              },
              tooltip: '清除对话',
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildIconButton({
    required IconData icon,
    required VoidCallback onPressed,
    String? tooltip,
  }) {
    return Tooltip(
      message: tooltip ?? '',
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onPressed,
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: Colors.white, size: 22),
          ),
        ),
      ),
    );
  }

  Widget _buildMessage(ChatMessage message) {
    Widget content;
    switch (message.type) {
      case MessageType.text:
        content = SelectableText(
          message.content,
          style: TextStyle(
            color: message.isUser ? Colors.white : const Color(0xFF2D3748),
            fontSize: 15,
            height: 1.5,
            letterSpacing: 0.2,
          ),
        );
        break;
      case MessageType.image:
        content = ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: Image.file(
            File(message.mediaPath!),
            width: 200,
            height: 200,
            fit: BoxFit.cover,
          ),
        );
        break;
      case MessageType.video:
        if (message.mediaPath != null) {
          if (!_videoControllers.containsKey(message.mediaPath)) {
            _videoControllers[message.mediaPath!] = VideoPlayerController.file(
              File(message.mediaPath!),
            )..initialize().then((_) {
                setState(() {});
              });
          }
          final controller = _videoControllers[message.mediaPath]!;
          content = ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: AspectRatio(
              aspectRatio: controller.value.aspectRatio,
              child: VideoPlayer(controller),
            ),
          );
        } else {
          content = const Text('视频路径无效');
        }
        break;
    }

    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        mainAxisAlignment: message.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          if (!message.isUser) ...[
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [_primaryGradientStart, _primaryGradientEnd],
                ),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: _primaryGradientStart.withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: const Icon(Icons.smart_toy, color: Colors.white, size: 18),
            ),
            const SizedBox(width: 8),
          ],
          Flexible(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                gradient: message.isUser
                    ? LinearGradient(
                        colors: [_userMessageGradientStart, _userMessageGradientEnd],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      )
                    : null,
                color: message.isUser ? null : _aiMessageBg,
                borderRadius: BorderRadius.only(
                  topLeft: const Radius.circular(20),
                  topRight: const Radius.circular(20),
                  bottomLeft: Radius.circular(message.isUser ? 20 : 4),
                  bottomRight: Radius.circular(message.isUser ? 4 : 20),
                ),
                boxShadow: [
                  BoxShadow(
                    color: (message.isUser ? _userMessageGradientStart : Colors.grey)
                        .withOpacity(0.2),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: content,
            ),
          ),
          if (message.isUser) ...[
            const SizedBox(width: 8),
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.blue.shade300, Colors.purple.shade300],
                ),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.blue.withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: const Icon(Icons.person, color: Colors.white, size: 18),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildTypingIndicator() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [_primaryGradientStart, _primaryGradientEnd],
              ),
              borderRadius: BorderRadius.circular(16),
            ),
            child: const Icon(Icons.smart_toy, color: Colors.white, size: 18),
          ),
          const SizedBox(width: 8),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: _aiMessageBg,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
                bottomLeft: Radius.circular(4),
                bottomRight: Radius.circular(20),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildTypingDot(0),
                const SizedBox(width: 4),
                _buildTypingDot(1),
                const SizedBox(width: 4),
                _buildTypingDot(2),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTypingDot(int index) {
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: 0.0, end: 1.0),
      duration: const Duration(milliseconds: 1200),
      curve: Curves.easeInOut,
      builder: (context, value, child) {
        final delay = index * 0.2;
        final animationValue = ((value + delay) % 1.0);
        final opacity = (animationValue < 0.5) ? animationValue * 2 : (1 - animationValue) * 2;
        return Container(
          width: 8,
          height: 8,
          decoration: BoxDecoration(
            color: _primaryGradientStart.withOpacity(0.3 + opacity * 0.5),
            shape: BoxShape.circle,
          ),
        );
      },
      onEnd: () {
        if (mounted && _isTyping) {
          setState(() {});
        }
      },
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            _buildInputIconButton(
              icon: Icons.image_outlined,
              onPressed: _handleImagePick,
              color: Colors.blue,
            ),
            const SizedBox(width: 8),
            _buildInputIconButton(
              icon: Icons.videocam_outlined,
              onPressed: _handleVideoPick,
              color: Colors.purple,
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(24),
                  border: Border.all(
                    color: _isInputFocused
                        ? _primaryGradientStart
                        : Colors.transparent,
                    width: 2,
                  ),
                ),
                child: TextField(
                  controller: _messageController,
                  focusNode: _focusNode,
                  decoration: InputDecoration(
                    hintText: '输入消息...',
                    hintStyle: TextStyle(color: Colors.grey.shade500),
                    border: InputBorder.none,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 12,
                    ),
                  ),
                  style: const TextStyle(fontSize: 15),
                  onSubmitted: _handleSubmitted,
                  textInputAction: TextInputAction.send,
                  onChanged: (_) => setState(() {}),
                ),
              ),
            ),
            const SizedBox(width: 8),
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: _messageController.text.trim().isEmpty
                      ? [Colors.grey.shade400, Colors.grey.shade500]
                      : [_primaryGradientStart, _primaryGradientEnd],
                ),
                borderRadius: BorderRadius.circular(24),
                boxShadow: _messageController.text.trim().isEmpty
                    ? null
                    : [
                        BoxShadow(
                          color: _primaryGradientStart.withOpacity(0.4),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
              ),
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: _messageController.text.trim().isEmpty
                      ? null
                      : () => _handleSubmitted(_messageController.text),
                  borderRadius: BorderRadius.circular(24),
                  child: Container(
                    padding: const EdgeInsets.all(12),
                    child: const Icon(Icons.send, color: Colors.white, size: 20),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInputIconButton({
    required IconData icon,
    required VoidCallback onPressed,
    required Color color,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onPressed,
        borderRadius: BorderRadius.circular(20),
        child: Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(20),
          ),
          child: Icon(icon, color: color, size: 22),
        ),
      ),
    );
  }
}
